package com.example.music.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.music.dto.AdminDto;
import com.example.music.entity.Admin;
import com.example.music.service.AdminService;
import com.example.music.utils.AjaxJson;
import com.example.music.utils.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    AdminService adminService;

    @PostMapping("login")
    public AjaxJson login(@RequestBody AdminDto admin) {
        List<Admin> admins = adminService.verifyPassword(admin);
        if (admins.size() > 0) {
            StpUtil.login(admins.get(0).getId());
            System.out.println(StpUtil.getTokenInfo());
            AdminDto adminDto = new AdminDto();
            adminDto.setUsername(admins.get(0).getName());
            adminDto.setToken(StpUtil.getTokenValue());
            return AjaxJson.getSuccessData(adminDto);
        }
        return AjaxJson.getError("用户名或密码错误");
    }
    @SaCheckLogin
    @GetMapping("test")
    public AjaxJson test() {
        return AjaxJson.getError("!@#");
    }

    @PostMapping("register")
    public ResponseMessage register(@RequestBody Admin admin){
        admin.setPassword(SecureUtil.md5(admin.getPassword()));
        adminService.add(admin);
        return ResponseMessage.ok();
    }

    @GetMapping("md5Password")
    public ResponseMessage md5Password() {
        adminService.md5Password();
        return ResponseMessage.ok(null);
    }
}
